<?php
namespace Admin\Controller;
use Think\Controller;
class NewsController extends CommonController {

	/**
	 * [index 查询数据库数据分配给模板展示]
	 */
	public function index(){
		$this -> assign('test','动态审核');
		$this->display();
	}

	/**
	 * [ajaxnews 页面ajax请求时, 提交到本方法, 并查询数据, 返回]
	 */
	public function ajaxnews(){
		if (IS_AJAX) {
			$news = M('news');

			// 接受关键字, 并拼接where 条件
			$keywords = I('post.keywords');
			if (!empty($keywords)) {
				$where['n.content'] = array('like', "%$keywords%");
			}
			$where['n.if_check'] = 0;

			// 三表联查, 返回数据
			$news_list = $news->alias('n')->join('zz_user u on u.user_id=n.user_id')->join('zz_user_info ui on ui.user_id=n.user_id')->field('n.content, n.news_id,n.time,n.if_check, u.username,ui.nickname, ui.photo')->limit('5')->where($where)->select();

			if ($news_list) {

				// 查到数据分配给模板前, 把if_check的字段更新为1,表示看过
				$news_id = '';
				foreach ($news_list as $val) {
					$news_id .= $val['news_id'].',';
				}
				$news_id = rtrim($news_id, ',');

				$data['news_id'] = array('in', $news_id);
				$news->where($data)->save(array('if_check'=>'1'));

				// 处理查到的值(时间戳格式化为Y-m-d h:i:s格式)
				foreach ($news_list as $key => $value) {
					$news_list[$key]['time'] = date('Y-m-d h:i:s',$value['time']);
				}

				$this->ajaxReturn($news_list);
			} else {
				$this->ajaxReturn(false);
			}
		} else {
			E('页面不存在');
		}

	}

	/**
	 * [delnews 接受ajax, 删除数据]
	 */
   public function delnews(){
		if (IS_AJAX) {
			$c = M();
			$c->startTrans();

			$news_id = I('post.news_id');
			$news = M('news');
			$info = $news->find($news_id);


			$res = $news->delete($news_id);
			// $res = true;
			if ($res && $info) {
				$where['public_time'] = $info['time'];
				$where['del_time'] = time();
				$where['user_id'] = $info['user_id'];
				$where['cont_type'] = 1;
				$where['if_read'] = 1;
				$check = M('check');
				$id = $check->add($where);
				if ($id) {
					$c->commit();
					$this->ajaxReturn('1');
				} else {

					$c->rollback();
					$this->ajaxReturn('0');
				}

			} else {
				$c->rollback();
				$this->ajaxReturn('0');
			}

		} else {

		}

	}


}
